package com.unism.common.schedulerTask;


import java.util.*;
import org.quartz.*;


public class SchedulerTaskSupport {
	
	/**
	 * 添加每X秒钟重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param futureSecond 延迟到将来时长(单位秒)以开始工作
	 * @param intervalInSeconds 重复工作间隔时长(秒)
	 * @param repeatCount  重复工作次数(如果小于0，将一直重复执行下去 , 如果是0执行一次，如果是1执行2次，依次类推)
	 * @return 工作任务Key  
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public static String addSecondlyJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int futureSecond,
			int intervalInSeconds ,
			int repeatCount) throws Exception {
		SchedulerTaskSupport.checkDelayStart(futureSecond) ;
		if(intervalInSeconds < 1){
			throw new Exception("重复工作间隔时长(单位秒)不能小于1秒)!") ;
		}
		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
		Date futureDate = DateBuilder.futureDate(futureSecond, DateBuilder.IntervalUnit.SECOND) ;
		Date startTime = DateBuilder.evenSecondDate(futureDate);
       
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .startAt(startTime)
	        .withSchedule(SimpleScheduleBuilder.simpleSchedule()
	                .withIntervalInSeconds(intervalInSeconds)
	                .withRepeatCount(repeatCount))
	        .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;
	}
	/**
	 * 添加每X分钟重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param futureSecond 延迟到将来时长(单位秒)以开始工作
	 * @param intervalInMinutes 重复工作间隔时长(分钟)
	 * @param repeatCount  重复工作次数(如果小于0，将一直重复执行下去 , 如果是0执行一次，如果是1执行2次，依次类推)
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public static String addMinutelyJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int futureSecond,
			int intervalInMinutes ,
			int repeatCount) throws Exception {
		SchedulerTaskSupport.checkDelayStart(futureSecond) ;
		if(intervalInMinutes < 1){
			throw new Exception("重复工作间隔时长(单位分钟)不能小于1分钟)!") ;
		}

		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
		Date futureDate = DateBuilder.futureDate(futureSecond, DateBuilder.IntervalUnit.SECOND) ;
		Date startTime = DateBuilder.evenSecondDate(futureDate);
       
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .startAt(startTime)
	        .withSchedule(SimpleScheduleBuilder.simpleSchedule()
	                .withIntervalInMinutes(intervalInMinutes)
	                .withRepeatCount(repeatCount))
	        .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;

	}
	/**
	 * 添加每X小时重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param futureSecond 延迟到将来时长(单位秒)以开始工作
	 * @param intervalInHour 重复工作间隔时长(小时)
	 * @param repeatCount  重复工作次数(如果小于0，将一直重复执行下去 , 如果是0执行一次，如果是1执行2次，依次类推)
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public static String addHourlyJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int futureSecond,
			int intervalInHour ,
			int repeatCount) throws Exception {
		SchedulerTaskSupport.checkDelayStart(futureSecond) ;
		if(intervalInHour < 1){
			throw new Exception("重复工作间隔时长(单位小时)不能小于1小时)!") ;
		}

		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
		Date futureDate = DateBuilder.futureDate(futureSecond, DateBuilder.IntervalUnit.SECOND) ;
		Date startTime = DateBuilder.evenSecondDate(futureDate);
       
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .startAt(startTime)
	        .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInHours(intervalInHour)
                .withRepeatCount(repeatCount))
            .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;
	}
	
	/**
	 * 添加每天某时某分重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param hour 某时(0-23之间(包括0与23))
	 * @param minute 某分(0-59之间(包括0与59))
	 * @throws Exception
	 */
//	表达式 意义 
//	"0 0 12 * * ?" 每天中午12点触发 
//	"0 15 10 ? * *" 每天上午10:15触发 
//	"0 15 10 * * ?" 每天上午10:15触发 
//	"0 15 10 * * ? *" 每天上午10:15触发 
//	"0 15 10 * * ? 2005" 2005年的每天上午10:15触发 
//	"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发 
//	"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发 
//	"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 
//	"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发 
//	"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发 
//	"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发 
//	"0 15 10 15 * ?" 每月15日上午10:15触发 
//	"0 15 10 L * ?" 每月最后一日的上午10:15触发 
//	"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发 
//	"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发 
//	"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发 
	@SuppressWarnings("unchecked")
	public static String addDailyJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int hour ,
			int minute) throws Exception {
		SchedulerTaskSupport.checkHour(hour) ;
		SchedulerTaskSupport.checkMinute(minute) ;
		
		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .withSchedule(CronScheduleBuilder.cronSchedule("0 " + minute + " " + hour + " * * ? *"))
	        .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;
	}
	
	/**
	 * 添加每周一、周二、周三、周四、周五各重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param hour 某时(0-23之间(包括0与23))
	 * @param minute 某分(0-59之间(包括0与59))
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static String addWorkingDayInWeekJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int hour ,
			int minute) throws Exception {
		SchedulerTaskSupport.checkHour(hour) ;
		SchedulerTaskSupport.checkMinute(minute) ;

		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .withSchedule(CronScheduleBuilder.cronSchedule("0 " + minute + " " + hour + " ? * MON-FRI" ))
	        .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;
	}
	/**
	 * 添加每一周的某一天某时某分重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param dayOfWeek 一周的某一天(1代表周一,依次类推)(取值1-7(包括1与7))
	 * @param hour 某时(0-23之间(包括0与23))
	 * @param minute 某分(0-59之间(包括0与59))
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static String addWeeklyJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int dayOfWeek,
			int hour ,
			int minute) throws Exception {
		SchedulerTaskSupport.checkHour(hour) ;
		SchedulerTaskSupport.checkMinute(minute) ;
		dayOfWeek = SchedulerTaskSupport.checkDayOfWeek(dayOfWeek);
		
		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .withSchedule(CronScheduleBuilder.cronSchedule("0 " + minute + " " + hour + " ? * " + dayOfWeek ))
	        .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;
	}
	/**
	 * 添加每月的某一天某时某分重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param dayOfMonth 一月的某一天(1-31之间(包括1与31))
	 * @param hour 某时(0-23之间(包括0与23))
	 * @param minute 某分(0-59之间(包括0与59))
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static String addMonthlyJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int dayOfMonth,
			int hour ,
			int minute) throws Exception {
		SchedulerTaskSupport.checkHour(hour) ;
		SchedulerTaskSupport.checkMinute(minute) ;
		SchedulerTaskSupport.checkDayOfMonth(dayOfMonth);
		
		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .withSchedule(CronScheduleBuilder.cronSchedule("0 " + minute + " " + hour + " " + dayOfMonth + " * ?"))
	        .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;
	}
	/**
	 * 添加每月的最后一天某时某分重复工作一次的工作任务，
	 * @param jobName 工作名称
	 * @param jobGroupName 工作组名称
	 * @param jobClass 工作类
	 * @param hour 某时(0-23之间(包括0与23))
	 * @param minute 某分(0-59之间(包括0与59))
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static String addLastDateOfMonthJob(
			String jobName, 
			String jobGroupName, 
			Class jobClass , 
			HashMap<String , Object> jobDataMap ,
			int hour ,
			int minute) throws Exception {
		SchedulerTaskSupport.checkHour(hour) ;
		SchedulerTaskSupport.checkMinute(minute) ;
		
		Scheduler sched = SchedulerTaskFactory.getSingleScheduler() ;
		
        JobDetail job = JobBuilder.newJob(jobClass)
            .withIdentity(jobName, jobGroupName)
            .build();
        SchedulerTaskSupport.setDataMap(job, jobDataMap) ;
        
        Trigger trigger = TriggerBuilder.newTrigger()
	        .withIdentity(jobName + "_trigger", jobGroupName + "_trigger")
	        .withSchedule(CronScheduleBuilder.cronSchedule("0 " + minute + " " + hour + " L * ?"))
	        .build();
        
        sched.scheduleJob(job, trigger);
        sched.start();

        return job.getKey().toString() ;
	}
	
	
	/**
	 * 设置参数数据
	 */
	private static void setDataMap(JobDetail job , HashMap<String , Object> jobDataMap){
		if(jobDataMap != null && jobDataMap.size() > 0){
			JobDataMap map = job.getJobDataMap();
			Set<Map.Entry<String , Object>> set = jobDataMap.entrySet() ;
			Iterator<Map.Entry<String , Object>> it = set.iterator() ;
			Map.Entry<String , Object> entry = null ;
			String key = null ;
			Object value = null ;
			while(it.hasNext()){
				entry = it.next() ;
				key = entry.getKey() ;
				value = entry.getValue() ;
				map.put(key, value);
			}
		}
	}
	
	/**
	 * 
	 * @param futureSecond
	 */
	private static void checkDelayStart(int futureSecond)throws Exception {
		if(futureSecond < 0){
			throw new Exception("延迟开始工作时长(单位秒)不能小于0!") ;
		}
	}
	
	/**
	 * 
	 * @param hour
	 * @throws Exception
	 */
	private static void checkHour(int hour)throws Exception {
		if(hour < 0 || hour >= 24){
			throw new Exception("重复工作的小时时间点取值必须在0-23之间(包括0与23)!") ;
		}
	}
	/**
	 * 
	 * @param minute
	 * @throws Exception
	 */
	private static void checkMinute(int minute)throws Exception {
		if(minute < 0 || minute >= 60){
			throw new Exception("重复工作的分钟时间点取值必须在0-59之间(包括0与59)!") ;
		}
	}
	/**
	 * 
	 * @param dayOfWeek
	 * @throws Exception
	 */
	private static int checkDayOfWeek(int dayOfWeek)throws Exception {
		if(dayOfWeek < 1 || dayOfWeek > 7){
			throw new Exception("重复工作的一星期的某一天取值必须在1(周一)-7(周日)间(包括1与7)!") ;
		}
		int d = 0 ;
		if(dayOfWeek == 1){
			d = DateBuilder.MONDAY ;
		}else if(dayOfWeek == 2){
			d = DateBuilder.TUESDAY ;
		}else if(dayOfWeek == 3){
			d = DateBuilder.WEDNESDAY ;
		}else if(dayOfWeek == 4){
			d = DateBuilder.THURSDAY ;
		}else if(dayOfWeek == 5){
			d = DateBuilder.FRIDAY ;
		}else if(dayOfWeek == 6){
			d = DateBuilder.SATURDAY ;
		}else if(dayOfWeek == 7){
			d = DateBuilder.SUNDAY ;
		}
		return d ;
	}
	/**
	 * 
	 * @param dayOfMonth
	 * @throws Exception
	 */
	private static void checkDayOfMonth(int dayOfMonth)throws Exception {
		if(dayOfMonth < 1 || dayOfMonth > 31){
			throw new Exception("重复工作一月某一天取值必须在1-31之间(包括1与31)!") ;
		}
	}
}
